package com.define.ssh.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.define.ssh.dao.UserInfoDao;
import com.define.ssh.model.UserInfo;
import com.define.ssh.util.Pager;

@Repository("userInfoDaoImpl")
public class UserInfoDaoImpl extends BaseDaoImpl<UserInfo, Long> implements
		UserInfoDao {

	@Override
	public UserInfo getUserInfoByLogin(String login) {
		String hql = "from UserInfo t where 1=1 and role in (select r.id from Role r)";
		hql += " and t.userCode='" + login + "'";
		return (UserInfo) getSession().createQuery(hql).uniqueResult();
	}

	@Override
	public boolean isExistByLogin(String login) {
		final String hql = "from UserInfo as user where lower(user.userCode) = lower(:userCode)";
		final UserInfo userInfo = (UserInfo) getSession().createQuery(hql)
				.setParameter("userCode", login).uniqueResult();
		if (userInfo != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据角色id删除 对应角色的用户
	 * 
	 * @param role_id
	 *            角色id
	 * @return
	 */
	@Override
	public void delUserInfoByRole(Long role_id) {
		String hql = "delete UserInfo t where 1=1 ";
		hql += " and t.role.id='" + role_id + "'";
		getSession().createQuery(hql).executeUpdate();
	}

	@Override
	public Pager findPagerByAccount(Pager pager) {
		final Criteria criteria = getSession().createCriteria(UserInfo.class);

		final String searchBy = pager.getSearchBy();
		final String keyword = pager.getKeyword();
		criteria.add(Restrictions
				.in("role.id", new Object[] { 1L, 2L, 3L, 4L }));
		if (StringUtils.isNotEmpty(searchBy) && StringUtils.isNotEmpty(keyword)) {
			final String[] sbs = searchBy.split(",");
			if (sbs.length == 2) {
				criteria.add(Restrictions.or(
						Restrictions.like(sbs[0], "%" + keyword + "%"),
						Restrictions.like(sbs[1], "%" + keyword + "%")));
			} else {
				criteria.add(Restrictions.like(searchBy, "%" + keyword + "%"));
			}
		}
		pager.setSearchBy("");
		pager = findPager(pager, criteria);
		pager.setSearchBy(searchBy);
		pager.setKeyword(keyword);
		return pager;
	}

	@Override
	public Pager findPagerByPowers(Pager pager, List<Integer> powers_list) {
		final Criteria criteria = getSession().createCriteria(UserInfo.class);
		criteria.add(Restrictions.in("power", powers_list.toArray()));
		pager = findPager(pager, criteria);
		return pager;
	}

}
